package com.dream.xcarrecorder.audio;

public class G711Player {

    public enum G711Type{
        G711_TYPE_A,
        G711_TYPE_U;
    }

    private final G711Type mType;
    private final short[] mPCMBuffer;
    private final PCMPlayer mPCMPlayer;

    private long mTimeTamp = 0L;

    public G711Player(G711Type g711Type,int buffer,int channelNum){
        this.mType = g711Type;
        this.mPCMPlayer = new PCMPlayer(buffer,8000,channelNum);
        this.mPCMBuffer = new short[buffer];
    }

    public void play(byte[] data,long timeTamp){
        play(data,0,data.length,timeTamp);
    }

    public void play(byte[] data,int offset,int size,long timeTamp){
        mTimeTamp = timeTamp;
        //附注，后期如果处理不正常的音频，可以不播放，直接计算PCM数据的播放时长，直接sleep也是比较可行的方案
        //播放时长 = PCM数据大小*1.0/(采样率 * 2 * 2);

        if (mType == G711Type.G711_TYPE_A){
            G711Utils.g711A2PCM(data,mPCMBuffer,offset,size);
        }else if (mType == G711Type.G711_TYPE_U){
            G711Utils.g711u2PCM(data,mPCMBuffer,offset,size);
        }

        mPCMPlayer.play(mPCMBuffer,size);
    }

    public long getTimeTamp(){
        return mTimeTamp;
    }

    public void close(){
        mPCMPlayer.stop();
    }

    public void cleanTimeTamp(){
        mTimeTamp = 0L;
    }
}
